﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MySpaceID.SDK;
using MySpaceID_OAuth.Core;
using MySpaceID.SDK.OAuth.Tokens;
using MySpaceID.SDK.Context;
using MySpaceID.SDK.Api;

namespace MySpaceID_OAuth
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["oauthreturn"] != null)
            {
                divLoggedOut.Visible = false;
                divLoggedIn.Visible = true;
                PopulateUserProfile();

            }
            else
            {
                divLoggedOut.Visible = true;
                divLoggedIn.Visible = false;
                CheckConsumerKey_Secret();
            }
        }
        private void CheckConsumerKey_Secret()
        {
            if (string.IsNullOrEmpty(Constants.ConsumerKey) || string.IsNullOrEmpty(Constants.ConsumerSecret))
            {
                lblErrorMessage.Visible = true;
                btnOAuth.Enabled = false;
                string format = "The following settings were not set: {0}. Please set them in /Core/Constants.cs in order to proceed with the sample.";
                string missingSettings = string.Empty;
                if (string.IsNullOrEmpty(Constants.ConsumerKey))
                    missingSettings += "ConsumerKey,";
                if (string.IsNullOrEmpty(Constants.ConsumerSecret))
                    missingSettings += "ConsumerSecret,";
                missingSettings = missingSettings.Remove(missingSettings.Length - 1);
                lblErrorMessage.Text = string.Format(format, missingSettings);

            }
            else
            {
                lblErrorMessage.Visible = false;
                btnOAuth.Enabled = true;
            }
        }
        protected void btnOAuth_Click(object sender, EventArgs e)
        {
            GetRequestToken();
        }

        private void PopulateUserProfile()
        {
            var requestTokenKey = Session["requesttokenkey"].ToString();
            var requestTokenSecret = Session["requesttokensecret"].ToString();
            var verifier = Request.QueryString["oauth_verifier"];
            //We assume here that the user has authorized the request token.
            var context = new OffsiteContext(Constants.ConsumerKey, Constants.ConsumerSecret);
            //Exchange the User-Authorized Request Token for an Access Token
            var accessToken = context.GetAccessToken(requestTokenKey, requestTokenSecret, verifier);
            //Now that we have an Access Token, we should use it for all subsequent calls. To do this, just set the following two properties.
            context.OAuthTokenKey = accessToken.TokenKey;
            context.OAuthTokenSecret = accessToken.TokenSecret;
            Session["accesstokenkey"] = accessToken.TokenKey;
            Session["accesstokensecret"] = accessToken.TokenSecret;
            Application["accesstokensecret"] = accessToken.TokenSecret;
            //Grab the basic profile of the user who authorized the token.
            var myspaceClient = new RestV1(context);
            var user = myspaceClient.GetCurrentUser();
            var profile = myspaceClient.GetFullProfile(user.UserId);

            imageProfile.ImageUrl = user.Image;
            lblAge.Text = profile.Age.ToString();
            lblCity.Text = profile.City;
            lblCountry.Text = profile.Country;
            lblGender.Text = profile.Gender;
            lblMarital.Text = profile.MaritalStatus;
            lblName.Text = user.Name;
            lblPostalCode.Text = profile.Postalcode;
            lblProfileUrl.Text = user.WebUri;
            lblRegion.Text = profile.Region;

            PopulatePhotos(myspaceClient, user.UserId);
        }

        private void PopulatePhotos(RestV1 myspaceClient, int userId)
        {
            var photos = myspaceClient.GetPhotos(userId);
            if (photos.Count > 0)
            {
                divPhotos.InnerHtml = "<ul>";
                foreach (var photo in photos.Photos)
                {
                    divPhotos.InnerHtml += string.Format("<li><img src='{0}' </></li>", photo.SmallImageUri);
                }
                divPhotos.InnerHtml += "</ul>";
            }
        }

        private void GetRequestToken()
        {
            var context = new OffsiteContext(Constants.ConsumerKey, Constants.ConsumerSecret);
            //Get a Request Token
            var callbackUrl = "http://localhost:9090/default.aspx?oauthreturn=true";
            var requestToken = context.GetRequestToken(callbackUrl);
            Session["requesttokenkey"] = requestToken.TokenKey;
            Session["requesttokensecret"] = requestToken.TokenSecret;
            
            //Get the MySpace authentication page for the user to go to in order to authorize the Request Token.
            var authenticationUrl = context.GetAuthorizationUrl(requestToken, callbackUrl);

            Response.Redirect(authenticationUrl);
        }
    }
}
